#include "mainwindow.h"
#include "ui_mainwindow.h"

#include "cardgraphicsitem.h"

#include "cardlistdock.h"
#include "carddisplaydock.h"
#include "cardlistmodel.h"

#include <QFile>

MainWindow *MainWindow::instance;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    instance = this;

    battleField = new QGraphicsScene(this);

    ui->graphicsView->setScene(battleField);

    //ui->graphicsView->scene()->items().front()->moveBy(60, 60);

    hand = new CardListModel(this);
    library = new CardListModel(this);
    graveyard = new CardListModel(this);

    CardListDock *handView = new CardListDock(hand, this);
    handView->setWindowTitle(tr("My Hand"));
    handView->connect(ui->actionViewHand, SIGNAL(toggled(bool)), SLOT(setVisible(bool)));
    ui->actionViewHand->connect(handView, SIGNAL(visibilityChanged(bool)), SLOT(setChecked(bool)));
    addDockWidget(Qt::BottomDockWidgetArea, handView);

    CardListDock *graveyardView = new CardListDock(graveyard, this);
    graveyardView->setWindowTitle(tr("My Graveyard"));
    graveyardView->connect(ui->actionViewGraveyard, SIGNAL(toggled(bool)), SLOT(setVisible(bool)));
    ui->actionViewGraveyard->connect(graveyardView, SIGNAL(visibilityChanged(bool)), SLOT(setChecked(bool)));
    graveyardView->setFloating(true);
    graveyardView->setVisible(false);

    CardListDock *libraryView = new CardListDock(library, this);
    libraryView->setWindowTitle(tr("My Library"));
    libraryView->connect(ui->actionViewLibrary, SIGNAL(toggled(bool)), SLOT(setVisible(bool)));
    ui->actionViewLibrary->connect(libraryView, SIGNAL(visibilityChanged(bool)), SLOT(setChecked(bool)));
    libraryView->setFloating(true);
    libraryView->setVisible(false);

    connect(ui->actionDraw, SIGNAL(triggered()), SLOT(drawCard()));
    library->connect(ui->actionShuffleLibrary, SIGNAL(triggered()), SLOT(shuffle()));

    CardDisplayDock *cardDisplay = new CardDisplayDock(this);
    addDockWidget(Qt::LeftDockWidgetArea, cardDisplay);
    cardDisplay->displayCard("0");

    QFile file("deck.deck");
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        while (!file.atEnd()) {
            QString line = file.readLine();

            int pos = line.indexOf('#');

            if (pos != -1) {
                line = line.left(pos);
            }

            line = line.trimmed();

            if (!line.isEmpty()) {
                library->addCard(new CardGraphicsItem(line));
            }
        }

    }


}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::resizeEvent(QResizeEvent *)
{
    QGraphicsView *view = ui->graphicsView;
    battleField->setSceneRect(0, 0, view->viewport()->width(), view->viewport()->height());
}

void MainWindow::drawCard()
{
    if (CardGraphicsItem *card = library->removeTop()) {
        hand->addCard(card);
    }
}
